// MiafeOneDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MiafeOne.h"
#include "MiafeOneDlg.h"
#include "umfh.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
HWND hDlg;

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
	
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMiafeOneDlg dialog
int icdev;
unsigned char sector;//M1 Card, the sector to operate,range: 0-15
unsigned char block;//M1 Card,the block to operate,range: 0-63



CMiafeOneDlg::CMiafeOneDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CMiafeOneDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CMiafeOneDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	hDlg=m_list1.m_hWnd;
}

void CMiafeOneDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CMiafeOneDlg)
	DDX_Control(pDX, IDC_LIST1, m_list1);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CMiafeOneDlg, CDialog)
	//{{AFX_MSG_MAP(CMiafeOneDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BTN_INIT, OnBtnInit)
	ON_BN_CLICKED(IDC_BTN_FINDCARD, OnBtnFindcard)
	ON_BN_CLICKED(IDC_BTN_LOADKEY, OnBtnLoadkey)
	ON_BN_CLICKED(IDC_VERIFYCARD, OnVerifycard)
	ON_BN_CLICKED(IDC_BTN_CARDFUNC, OnBtnCardfunc)
	ON_BN_CLICKED(IDC_BTN_DEVFUNC, OnBtnDevfunc)
	ON_BN_CLICKED(IDC_HALT, OnHalt)
	ON_BN_CLICKED(IDC_BTN_CLOSE, OnBtnClose)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMiafeOneDlg message handlers

BOOL CMiafeOneDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	icdev=-1;//
	sector=3;
	block=12;

	// TODO: Add extra initialization here
//	m_list1.AddString("11111111111111111111111111111111111111111111111111111111111");
//	::SendDlgItemMessage(m_list1.m_hWnd, IDC_LIST1, LB_SETHORIZONTALEXTENT, 500, 0);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CMiafeOneDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CMiafeOneDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CMiafeOneDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CMiafeOneDlg::OnBtnInit() 
{
	// TODO: Add your control notification handler code here
	icdev=fw_init(100,9600);
	
	if((int)icdev<=0)
	{
		show("Init Com Error!");
	}
	else
	{
		show("Init Com OK!");
	}
	fw_beep((int)icdev,10);


	return;
}

void CMiafeOneDlg::OnBtnFindcard() 
{
	// TODO: Add your control notification handler code here
	
	if(0==CheckLinkState())
		return;

	int st;
	CString linstr;

	unsigned long cardsnr;
	st=fw_card(icdev,1,&cardsnr);//find card with multy card
    if(st!=0)
	{
   	   show("Find Card Error!");
       return;
	}
	else
	{
		show("Find Card Ok!");
	    linstr.Format("%u",cardsnr);
	    show(linstr);
	}
}

void CMiafeOneDlg::OnBtnLoadkey() 
{
	// TODO: Add your control notification handler code here
	if(0==CheckLinkState())
		return;

	//load key
  int st;
  unsigned char keyA[6]={0xff,0xff,0xff,0xff,0xff,0xff};
  st=fw_load_key(icdev,0,sector,keyA);//load keyA
  if(st!=0)
	 show("Load Key Error!");
  else
	 show("Load Key Ok!");	
}

void CMiafeOneDlg::OnVerifycard() 
{
	// TODO: Add your control notification handler code here
	if(0==CheckLinkState())
		return;

	//authentication key      
	int st;
	st=fw_authentication(icdev,0,sector);
    if(st!=0)
   	   show("Auth Card Error!");
    else
	   show("Auth Card Ok!");
}

void CMiafeOneDlg::OnBtnCardfunc() 
{
	// TODO: Add your control notification handler code here

	if(0==CheckLinkState())
		return ;

	//card function
	int st;
    unsigned char pieceaddr=1;
	unsigned long value;
    CString linstr;
    
	unsigned char keya[7]={0xff,0xff,0xff,0xff,0xff,0xff};
	unsigned char keyb[7]={0xff,0xff,0xff,0xff,0xff,0xff};
	
	unsigned char datachar[40]={'3','4','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3','3'};
	
	
	int i;
	unsigned char databuff[17]={0};
	char databuff2[33]={0};



	unsigned char ctrlword[4]={0xFF,0x07,0x80,0x69};

   
	//write data  
	for (i=0;i<16;i++)
	{
		databuff[i]='M';
	}
	st=fw_write(icdev,block,databuff);
    if(st!=0)
	{
		show("Write Card Error!");
		return;
	}
    else
	{
		show("Write Card Ok!");	
		hex_a((unsigned char *)databuff2,databuff,32);
		show(databuff2);
	}

	 //read data      
	st=fw_read(icdev,block,databuff);
    if(st!=0)
		show("Read Card Error!");
    else
	{
		show("Read Card Ok!");
		memset(databuff2,0,32);
		hex_a((unsigned char *)databuff2,databuff,32);

		show(databuff2);
	}

 	value=1000;

    st= fw_initval(icdev, block, value);
	if (st!=0)
	{
		show("fw_initval error");
	    linstr.Format("%d",st);
	    show(linstr);
		return;
	}
	show("fw_initval ok");

	value=300;
	st= fw_increment( icdev,block,value)||fw_transfer(icdev,block);
	if (st!=0)
	{
		show("fw_increment error");
		return;
	}
	show("fw_increment ok");
	value=200;

    st= fw_decrement( icdev,block,value)||fw_transfer(icdev,block);
	if (st!=0)
	{
		show("fw_decrement error");
		return;
	}
	show("fw_decrement ok");

    st= fw_readval(icdev,block,&value);
	if (st!=0)
	{
		show("fw_readval error");
		return;
	}
	show("fw_readval ok");
	linstr.Format("%d",value);
	show(linstr);

    st= fw_changeb3(icdev,sector,keya,ctrlword,0,keyb)//should better don't change the parameter 4,5,6, keep the same as original card
		||fw_halt(icdev);
	if (st!=0)
	{
		show("fw_changeb3 error");
	    linstr.Format("%d",st);
	    show(linstr);
		return;
	}
	show("fw_changeb3 ok");

	return;
}

void CMiafeOneDlg::OnBtnDevfunc() 
{
	// TODO: Add your control notification handler code here

	if(0==CheckLinkState())
		return ;
		
 // device function          
	unsigned char key[]={'1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f',0};
    unsigned char sour[]={'a','b','c','d','e','f','1','2','3','4','5','6','8','7','9','0',0};

	unsigned char dest[16];
	int st;


    CString linstr;
	unsigned char linchar[17];
	unsigned char timestr[17];



    memset(linchar,0,16);
	st= fw_getver(icdev,linchar);//get device version
	if (st!=0)
	{
		show("fw_getver error");
	    linstr.Format("%d",st);
	    show(linstr);
		return;
	}
	show("fw_getver ok");
	show(linchar);
	
    linchar[0]=0x45;
    linchar[1]=0x75;
    linchar[3]=0x55;
    linchar[4]=0x65;
    linchar[2]=0x35;
	linchar[5]=0;
	st= fw_swr_eeprom(icdev,24,15,linchar);//write EEPROM (0-25)
	if (st!=0)
	{
		show("fw_swr_eeprom error");
	    linstr.Format("%d",st);
	    show(linstr);
		return;
	}
	show("fw_swr_eeprom ok");

	linchar[0]=0;
	st= fw_srd_eeprom(icdev,500,5,linchar);//read
	if (st!=0)
	{
		show("fw_srd_eeprom error");
	    linstr.Format("%d",st);
	    show(linstr);
		return;
	}
	show("fw_srd_eeprom ok");



	st= fw_reset((HANDLE)icdev,2);//device reset
	if (st!=0)
	{
		show("fw_reset error");
	    linstr.Format("%d",st);
	    show(linstr);
		return;
	}
	show("fw_reset ok");


	hex_a(timestr,linchar,7);
	show(linchar);



    //des test
/*	st=fw_des(key,sour,dest,0);
    if (st!=0)
	{
		show("fw_des error");
		return;
	}
	show("fw_des ok");
	dest[16]=0;
	show(dest);

	show(sour);
    sour[0]=0;

	st=fw_des(key,dest,sour,1);
    if (st!=0)
	{
		show("fw_des error");
		return;
	}
	show("fw_des ok");
	sour[16]=0;
	show(sour);*/

}

void CMiafeOneDlg::OnHalt() 
{
	// TODO: Add your control notification handler code here
    int st;
	st=fw_halt(icdev);
    if(st!=0)
   	   show("Halt Card Error!");
    else
	   show("Halt Card Ok!");	


}

void CMiafeOneDlg::show(CString datastr)
{
	m_list1.AddString(datastr);
	m_list1.SetCurSel(m_list1.GetCount()-1);
	MSG message;
	if (::PeekMessage(&message,NULL,0,0,PM_REMOVE))
	{
		::TranslateMessage(&message);
		::DispatchMessage(&message);
	}
}

LRESULT CMiafeOneDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
	// TODO: Add your specialized code here and/or call the base class
	switch(message)
	{
	case WM_INITDIALOG:
		{
		/*	HWND hDlg=this->m_list1.m_hWnd;
			HDC hdc;
			int i;
			TCHAR str[100];
			for(i = 0; i < 100; i++)
			{
				wsprintf(str, "This is a very very very very very long sentence - line %d", i + 1);
				SendDlgItemMessage(IDC_LIST1, LB_ADDSTRING, 0, (LPARAM)str);
				
			}
			SendDlgItemMessage(IDC_LIST1, LB_SETHORIZONTALEXTENT, 500, 0);
		*/
		}
		break;
	}
	return CDialog::WindowProc(message, wParam, lParam);
}

/*
 * test reader link status
 */
int CMiafeOneDlg::CheckLinkState()
{
	if(icdev<=0)
	{
		show("Reader is not linked,please link first!");
		return 0;
	}
	else
		return 1;

}
/*
 * Close device
 * reader should be closed before next link
 */
void CMiafeOneDlg::OnBtnClose() 
{
	// TODO: Add your control notification handler code here
	if(fw_exit(icdev))
		show("Device Close Error!");
	else
	{
		show("Device Has Closed!");
		icdev=-1;
	}
}
